let nop = function () {
};

function rpc(event, data) {
    let param = {};
    event && (param.e = event);
    data && (param.d = data);
    pomelo.request('room.roomHandler.z', param, function (msg) {
        if (Object.keys(msg).length > 0) {
            console.log("发送请求失败: " + msg.code);
        }
    });
}


class PomeloMgr {

    constructor() {

    }

    init() {
        if (consts.isYiLe) {
            //牛气冲天地址
            this.url = window.consts.yileUri;
        } else {
            //胡大王地址
            // HTTP_SERVER = 'http://39.108.151.212:9000';
            // HTTP_SERVER = "http://192.168.0.103:9000";
            this.url = window.consts.uri;
        }


        console.log(consts.isYiLe + ":服务器地址:" + this.url);
    }

    /**
     *
     */
    httpGET(path, data, handler, extraUrl) {
        let xhr = cc.loader.getXMLHttpRequest();
        let isTimeout = false;
        let str = "?";
        for (let k in data) {
            if (str != "?") str += "&";
            str += k + "=" + data[k];
        }
        if (extraUrl == null) extraUrl = this.url;
        let requestURL = extraUrl + path + (str === '?' ? '' : encodeURI(str));
        // console.log("RequestURL:" + requestURL);
        xhr.open("GET", requestURL, true);
        //设置请求头
        if (cc.sys.isNative) xhr.setRequestHeader("Accept-Encoding", "gzip,deflate", "text/html;charset=UTF-8");

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && !isTimeout) {
                isTimeout = true;
                if (xhr.status >= 200 && xhr.status < 300) {
                    // console.log("http res(" + xhr.responseText.length + "):" + xhr.responseText);
                    let ret = xhr.responseText;
                    try {
                        ret = JSON.parse(xhr.responseText);
                        ret.code = parseInt(ret.code);
                    } catch (e) {
                        handler({code: -888, errmsg: "不是json对象"});
                        return;
                    }
                    console.log(path, {
                        msgLen: xhr.responseText.length,
                        url: requestURL,
                        result: ret
                    });
                    if (handler !== null) handler(ret);
                } else {
                    console.log(path, {
                        url: requestURL,
                        result: {code: 41, errmsg: "服务器忙，请稍后在试"}
                    });
                    handler({code: 41, errmsg: "服务器忙，请稍后在试"});
                }
            }
        };
        xhr.send();

        setTimeout(function () {
            if (!isTimeout) {
                isTimeout = true;
                handler({code: 42, errmsg: "连接失败，请稍后在试"});
            }
        }, 5000);
        return xhr;
    }

    /**
     * 发送
     * @param options
     * @param cb
     */
    httpSend(options, cb) {
        cb = cb || nop;
        let xhr = cc.loader.getXMLHttpRequest();
        let isTimeout = false;
        let url = options.url || this.url;
        let path = options.path || '/';
        let context = '';
        let URI = '';

        if(!/post/i.test(options.method)){
            context = this.queryString(options.data);
        }

        URI = url + path + context;

        console.log(URI);

        xhr.open(options.method || "GET", URI, true);

        //设置请求头
        if (cc.sys.isNative && /get/i.test(options.method)) {
            xhr.setRequestHeader("Accept-Encoding", "gzip,deflate", "text/html;charset=UTF-8");
        }
        if (/post/i.test(options.method)) {
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        }

        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && !isTimeout) {
                isTimeout = true;
                if (xhr.status >= 200 && xhr.status < 300) {
                    let ret = xhr.responseText;
                    try {
                        ret = JSON.parse(xhr.responseText);
                        ret.code = parseInt(ret.code);
                    } catch (e) {
                        ret = {
                            code: -888,
                            msg: "不是json对象",
                            result: xhr.responseText
                        };
                    }

                    console.log(path, {
                        url: URI,
                        params: options.data,
                        msgLen: xhr.responseText.length,
                        result: ret
                    });

                    if (cb !== null)
                        cb(parseInt(ret.code), ret);
                } else {
                    console.log(path, {
                        url: URI,
                        result: [41, "服务器忙，请稍后在试"]
                    });
                    cb(41, "服务器忙，请稍后在试");
                }
            }
        };

        if(/post/i.test(options.method)){
            xhr.send("param=" + JSON.stringify(options.data || {}));
        } else {
            xhr.send();
        }


        setTimeout(function () {
            if (!isTimeout) {
                isTimeout = true;
                console.log(path, {
                    url: URI,
                    result: {code: 42, errmsg: "连接超时，请稍后在试"}
                });
                cb(42, "连接超时，请稍后在试");
            }
        }, 10000);
    }



    /**
     * 将参数转找成链接形式
     * @param context
     * @return {*}
     */
    queryString(context) {
        if (!context || (typeof context !== "object")) {
            return "";
        }
        let str = "?";
        for (let k in context) {
            str === "?" || (str += "&");
            str += k + "=" + context[k];
        }
        return str;
    }

    /**
     * post请求
     * @param event  接口名
     * @param data   数据对象
     * @param cb     回调cb(code, msg);
     */
    post(event, data, cb){
        data.account = cc.user.account;
        data.sign = cc.user.sign;
        data.cid = consts.cid;
        data.uid = cc.user.uid;
        this.httpSend({
            method: "POST",
            path: '/' + event,
            data: data,
        }, cb);
    }

    /**
     * 检查版本信息
     * @param data
     * @param cb
     */
    checkVersion(data, cb) {
        this.httpSend({
            method: "GET",
            path: '/check_version',
            data: data
        }, cb);
    }

    /**
     *
     * @param code
     * @param os
     * @param cb
     */
    wechat_auth(code, os, cb) {
        this.httpGET("/wx_login", {code: code, os: os}, cb);
    }

    /**
     * 更新地理位置
     */
    updateLocation() {
        console.log("更新地理位置" + this.isLocation);
        if (!this.isLocation) {
            var address = cc.vv.map.getAddrStr();
            var self = this;
            if (address && address.errcode == 0) {
                this.httpSend({
                    method: "POST",
                    path: "/update_location",
                    data: {
                        account: cc.user.account,
                        sign: cc.user.sign,
                        location: JSON.stringify(address)
                    }
                }, function (code, ret) {
                    if (code === 200) {
                        console.log("提交位置成功");
                        self.isLocation = true;
                    } else {
                        console.log(ret.code + "提交位置失败：" + cc.Code[ret.code]);
                    }
                });
            }
        }
    }

    /**
     * 绑定代理
     * @param code 代理邀请码
     * @param cb   回调
     */
    bindDealer(code, cb) {
        this.httpSend({
            path: "/bind_dealer",
            data: {
                account: cc.user.account,
                sign: cc.user.sign,
                user_code: code
            }
        }, cb);
    }

    /**
     * 支付接口
     * @param id 商品id
     * @param cb 回调
     */
    buy(id, cb) {
        this.httpSend({
            path: "/buy_diamond",
            data: {
                account: cc.user.account,
                sign: cc.user.sign,
                user_id: cc.user.uid,
                os: cc.sys.os === cc.sys.OS_IOS ? "ios" : "android",
                pay_type: "30", //微信支付，22=支付宝支付
                id: id,
            }
        }, cb);
    }

    /**
     * 查询订单是否支付成功
     * @param orderSn 订单号
     * @param cb
     */
    queryOrder(orderSn, cb) {
        this.httpSend({
            path: "/query_order",
            data: {
                account: cc.user.account,
                sign: cc.user.sign,
                order_sn: orderSn
            }
        }, cb);
    }

    /**
     * 获取房间列表
     * @param cb
     */
    getRoomList(cb) {
        this.httpGET("/getRoomList", {
            uid: cc.user.uid,
            account: cc.user.account,
            sign: cc.user.sign,
        }, function (data) {
            cb(data.code, data.res);
        })
    }

    /**
     * 获取一个房间的战绩
     * @param cb
     */
    getOneHistory(uuid, cb) {
        this.httpGET("/getOneHistory", {
            account: cc.user.account,
            sign: cc.user.sign,
            uuid: uuid
        }, function (data) {
            cb(data.code, data.result);
        });
    }

    /**
     * 获取历史记录
     */
    getHistory(cb) {
        this.httpGET("/getHistory", {
            uid: cc.user.uid,
            account: cc.user.account,
            sign: cc.user.sign,
            page: 0
        }, function (data) {
            cb(data.code, data.res);
        });
    }

    getHistoryDetail(id, cb) {
        this.httpGET("/getRoomHistory", {
            id: id,
            account: cc.user.account,
            sign: cc.user.sign
        }, cb);
    }

    /**
     * 获取身份信息
     * @param account
     * @param cb
     */
    guest_auth(account, cb) {
        this.httpGET("/guest", {account: account}, cb);
    }

    /**
     * 获取账户信息
     * @param account
     * @param sign
     * @param cb
     */
    getInfo(account, sign, cb) {
        this.httpGET("/get_user_info", {account: account, sign: sign}, cb);
    }

    /**
     * 创建房间
     * @param data
     * @param cb
     */
    createRoom(data, cb) {
        this.httpSend({
            path: '/create_infinite_room',
            method: "POST",
            data: data
        }, cb);
    }

    /**
     * 加入房间
     * @param rid 房间号
     * @param cb
     */
    joinRoom(rid) {
        cc.utils.openLoading("玩命加入房间: " + rid);
        this.httpSend({
            path: '/join_infinite_room',
            method: "POST",
            data: {
                account:cc.user.account,
                sign:cc.user.sign,
                uid:cc.user.uid,
                rid:rid,
                cid:consts.cid
            }
        }, function (code, msg) {
            console.log(arguments);
            if(code === 200){
                console.log("开始连接", rid);
                cc.pomelo.connect(msg.host, msg.port, rid);
            } else {
                cc.utils.openErrorTips(code);
            }
        });
    }

    /**
     * 连接房间服务器
     * @param host
     * @param port
     * @param rid
     */
    connect(host, port, rid) {
        let self = this;
        this.host = host;
        this.port = port;
        window.pomelo.removeAllListeners();

        function join(cb) {
            self.httpSend({
                path: '/join_infinite_room',
                method: "POST",
                data: {
                    account:cc.user.account,
                    sign:cc.user.sign,
                    uid:cc.user.uid,
                    rid:rid,
                    cid:consts.cid
                }
            }, function (code, msg) {
                if(code === 200){
                    init(cb);
                } else if (parseInt(code) === 5001){
                    cc.pomelo.emit("notExists");
                } else {
                    cc.utils.openErrorTips(code, function () {
                        cc.director.loadScene("hall");
                    });
                }
            });
        }

        /**
         * 初始连接服务器
         */
        function init(cb) {
            window.pomelo.init({
                host: host,
                port: port,
                log: true,
                reconnect: false,
            }, function () {
                login(cb);
                window.pomelo.on("disconnect", disconnect);
            });
        }


        /**
         * 登录房间
         */
        function login(cb) {
            window.pomelo.request('room.roomHandler.login', {
                account:cc.user.account,
                sign:cc.user.sign,
                rid:rid,
                uid:cc.user.uid
            }, function (msg) {
                if(isNaN(msg)){
                    let code = parseInt(msg.code);
                    let type = parseInt(msg.type); //游戏类型
                    if (code === 200) {
                        cb(type);
                    } else {
                        cc.utils.openErrorTips(code, function () {
                            cc.director.loadScene("hall");
                        });
                        self.disconnect();
                    }
                } else {
                    cc.utils.openErrorTips(msg, function () {
                        cc.director.loadScene("hall");
                    });
                    self.disconnect();
                }
            });
        }

        /**
         * 掉线触发函数
         */
        function disconnect() {
            console.log("掉线");
            self.disconnectCb && self.disconnectCb(); //调用离线回调
            window.pomelo.off('disconnect');
            cc.utils.openLoading("玩命连接...");
            setTimeout(function () {
                join(function () {
                    self.getRoomInfo(); //获取房间数据
                    cc.utils.closeTips();
                })
            }, 100);
        }

        init(function (type) {
            if(type === 5){
                cc.director.loadScene("PDKScene");
            } else {
                if(type === 6){
                    cc.director.loadScene("PSZScene");
                }else{
                    cc.director.loadScene("niuniu");
                }
            }
        });
    }

    //断开连接
    disconnect(cb) {
        console.log("主动断开连接");
        cb = cb || nop;
        cc.pomelo.off('disconnect');
        window.pomelo.disconnect(cb);
    }

    /**
     * 设置一个离线监听函数
     */
    setDisconnect(cb){
        this.disconnectCb = cb;
    }

    //添加监听
    on(route, cb) {
        pomelo.on(route, cb);
    }

    //移除监听
    off(route, cb) {
        pomelo.off(route, cb);
    }

    //发送事件
    emit(event, data) {
        window.pomelo.emit(event, data);
    }

    /**
     * 获取房间数据
     */
    getRoomInfo() {
        rpc('roomInfo');
    }

    /**
     * 解散房间
     * 只有房主才能解散房间
     * @param uid 玩家uid
     */
    dismiss() {
        rpc('dismiss');
    }

    okDismiss() {
        rpc('okDismiss');
    }

    notDismiss() {
        rpc('notDismiss');
    }

    /**
     * 申请解散房间
     * 只有正在玩的人才能解散房间
     */
    applyDismiss() {
        rpc('applyDismiss');
    }

    /**
     * 离开房间
     * 只有游客和房间未开始时，才能离开房间
     * @param uid  玩家uid
     */
    leave() {
        rpc('leave', "data");
    }

    /**
     * 坐下
     */
    sitDown() {
        rpc('sitDown');
    }

    /**
     * 准备
     */
    ready() {
        rpc('ready');
    }

    /**
     * 取消准备
     */
    unready() {
        rpc('unready');
    }

    /**
     * 开始
     */
    start() {
        rpc('gameStart');
    }

    /**
     * 发送表情
     */
    emoji(id) {
        rpc('emoji', id);
    }

    /**
     * 聊天
     */
    chat(str) {
        if (str === '' || str === undefined || str === null) {
            console.log("聊天信息不能为空 chat = " + str)
        } else {
            rpc('chat', str);
        }
    }

    /**
     * 语音
     * @param msg 语音
     * @param time 语音时间
     */
    voice(msg, time) {
        rpc('voice', [msg, time]);
    }

    /**
     * 常用语
     */
    cWord(id) {
        rpc('cWord', id);
    }

    /**
     * 发送动画，扔的动画
     * @param suid 开始位置
     * @param euid 结束位置
     * @param id 动画id
     */
    animate(suid, euid, id) {
        rpc('animate', [suid, euid, id]);
    }

    /**
     * 设置托管
     */
    tuoGuang() {
        rpc('tuoGuang');
    }

    /**
     * 发送消息
     * @param event
     * @param data
     */
    send(event, data) {
        let param = {};
        event && (param.e = event);
        data && (param.d = data);
        window.pomelo.request('room.roomHandler.s', param, function (msg) {
            if (Object.keys(msg).length > 0) {
                console.log("发送请求失败: " + msg.code);
            }
        });
    }
}

module.exports = new PomeloMgr();

